package com.example.spring.multi.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 当前请求信息的封装
 *
 * @author xiaohan.yuan
 */
public class RequestUtil {

    private static final String COOKIE_KEY_HOUSE = "current-house";

    /**
     * 获取request
     *
     * @return javax.servlet.http.HttpServletRequest
     * @author xiaohan.yuan
     */
    public static HttpServletRequest getRequest() {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }

        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }


    /**
     * 获取cookie
     *
     * @return javax.servlet.http.Cookie[] 当前请求的cookie
     * @author xiaohan.yuan
     */
    public static Cookie[] getCookie() {
        return RequestUtil.getRequest().getCookies();
    }


    /**
     * 获取当前房屋的id
     *
     * @return java.lang.String
     * @author xiaohan.yuan
     */
    public static String getHouseId() {
        return getCookieValue(COOKIE_KEY_HOUSE);
    }

    /**
     * 根据名字获取cookie
     *
     * @param name cookie的key
     * @return java.lang.String
     * @author xiaohan.yuan
     */
    public static String getCookieValue(String name) {
        return getCookieKeyValueMap().get(name);
    }


    /**
     * 将cookie分组
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author xiaohan.yuan
     */
    private static Map<String, String> getCookieKeyValueMap() {
        return Arrays.stream(getCookie()).collect(
                Collectors.toMap(Cookie::getName, Cookie::getValue, (v1, v2) -> v2));
    }

}
